package game

import (
	"errors"
	"strings"
	"time"

	"gitee.com/shiwjlinux/game-manager/common"
	"github.com/sirupsen/logrus"
)

func NewGameSet() *GameSet {
	return &GameSet{
		GameItemInfo: []*Game{},
	}
}

type GameSet struct {
	GameItemInfo []*Game `json:"game_item_info"`
	Total        int64   `json:"total"`
}

func NewGame() *Game {
	return &Game{}
}

func (s *GameSet) String() string {
	return common.ToJsonString(s)
}

type Game struct {
	GameName     string `json:"game_name"`
	PackageName  string `json:"package_name" validate:"required"`
	Uid          int64  `json:"uid"`
	RegisterType int64  `json:"register_type"`
	MultiSync    int64  `json:"multi_sync"`
	StorageType  string `json:"storage_type"`
}

func (g *Game) GetUidByPackageName() int64 {
	return g.Uid
}

func (g *Game) GetUid() int64 {
	return g.Uid
}

func (g *Game) WithUidM1() *Game {
	if g.Uid > 10000 {
		g.Uid = g.Uid - 10000
	}
	return g
}

func (g *Game) String() string {
	return common.ToJsonString(g)
}

type GameENV string

const (
	GameENV_AIC          GameENV = "aic"
	GameENV_SelfBuilding GameENV = "SelfBuilding"
)

func (g *Game) GetEnv() (string, error) {
	// cmd := []string{"getprop ro.aic.instance.id"}
	cmd := []string{"echo"}

	result := common.RunCommand(common.SH, cmd, 5*time.Second)
	if result.Err != nil {
		return "", result.Err
	}

	if result.Stderr != nil {
		logrus.Errorf("GetEnv failed: %s", result.Stderr)
		return "", result.Stderr
	}

	if result.Code != 0 {
		return "", errors.New("GetEnv failed: result.Code!=0")
	}

	if strings.Contains(result.Stdout, "aic") {
		return string(GameENV_AIC), nil
	}
	if result.Stdout == "" {
		return string(GameENV_SelfBuilding), nil
	}

	return result.Stdout, nil
}
